package com.example.zp.jcenterupload;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.View;

import com.example.zp.jcenterupload.base.ActionBarActivity;
import com.example.zp.jcenterupload.chart.LinearChartActivity;
import com.example.zp.jcenterupload.http.IndicatorInterceptor;
import com.example.zp.jcenterupload.http.JsonDataRequest;
import com.example.zp.jcenterupload.http.Test;
import com.example.zp.jcenterupload.http.UserBean;
import com.example.zp.jcenterupload.sortrecyclerview.LinearRecyclerActivity;
import com.leaf.u.basehttp.http.HttpCallback;
import com.leaf.u.basehttp.http.LeafHttpClient;
import com.leaf.u.basehttp.http.okimpl.LeafRequest;
import com.leaf.u.basehttp.http.response.ErrorResponse;
import com.leaf.u.basehttp.http.response.SuccessResponse;
import com.pumpkin.navigation.ActionBar;
import com.pumpkin.navigation.ActionBarLayout;
import com.pumpkin.navigation.menu.TextMenu;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;

public class MainActivity extends ActionBarActivity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    protected void onCreateActionBar(ActionBar actionBar) {
        super.onCreateActionBar(actionBar);
        actionBar.addMenu(getTextMenu());
        actionBar.setCustomMenu(getTextMenuCenter());
        actionBar.addMenu(getTextMenuRight());
    }

    private TextMenu getTextMenuRight() {
        TextMenu marstMenu = new TextMenu(this);
        marstMenu.setText("右边");
        marstMenu.setTextColor(0xFFFFFFFF);
        marstMenu.setTextSize(18);
        marstMenu.setGravity(ActionBarLayout.Gravity.RIGHT);
        marstMenu.setMarginLeft(10);
        return marstMenu;
    }

    @NonNull
    private TextMenu getTextMenuCenter() {
        TextMenu marstMenu = new TextMenu(this);
        marstMenu.setText("12321");
        marstMenu.setTextColor(0xFFFFFFFF);
        marstMenu.setTextSize(18);
        marstMenu.setGravity(ActionBarLayout.Gravity.CENTER);
        marstMenu.setMarginLeft(10);
        return marstMenu;
    }

    @NonNull
    private TextMenu getTextMenu() {
        TextMenu marstMenu = new TextMenu(this);
        marstMenu.setText("首");
        marstMenu.setTextColor(0xFFFFFFFF);
        marstMenu.setTextSize(18);
        marstMenu.setGravity(ActionBarLayout.Gravity.LEFT);
        marstMenu.setMarginLeft(10);

        return marstMenu;
    }


    private void request() {

        String url1 = "http://192.168.2.57/rf_web/security/login";
        String url2 = "http://192.168.2.57/rf_web/rfweb/rfController/WMSRF_UR_QueryLoginMessage";


//        username	nora
//        password	123456
//        language	zh_CN
        LeafRequest cookie = new LeafRequest();
        cookie.url(url1)
                .post()
                .put("username", "eileen520")
                .put("password", "123456")
                .put("language", "zh_CN");


        final OkHttpClient okHttpclient = new OkHttpClient.Builder()
                .cookieJar(new CookieJar() {
                               private final HashMap<String, List<Cookie>> cookieStore = new HashMap<>();

                               @Override
                               public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
                                   cookieStore.put(url.host(), cookies);
                               }

                               @Override
                               public List<Cookie> loadForRequest(HttpUrl url) {
                                   List<Cookie> cookies = cookieStore.get(url.host());
                                   return cookies != null ? cookies : new ArrayList<Cookie>();
                               }
                           }
                ).build();

        LeafHttpClient.create(okHttpclient)
                .newCall(cookie)
                .addInterceptor(new IndicatorInterceptor(this))
                .execute(new HttpCallback<String>() {
                    @Override
                    public void onSuccess(SuccessResponse<String> response) {
                        request2(okHttpclient);
                    }

                    @Override
                    public void onFailed(ErrorResponse response) {

                    }
                });

    }

    private void request2(OkHttpClient okHttpclient) {
        List<String> sysConfigKeys = new ArrayList<>();
        sysConfigKeys.add("SYS_WM_PO_TYPE");
        sysConfigKeys.add("SYS_WM_QUALIFY");
        final JsonDataRequest request = new JsonDataRequest();
        request.post()
                .path("WMSRF_UR_QueryLoginMessage")
                .putJsonData("userCode", "nora")
                .putJsonData("password", "123456")
                .putJsonData("language", "zh_CN")
                .putJsonData("sysConfigKeys", sysConfigKeys);

        LeafHttpClient.create(okHttpclient)
                .newCall(request)
                .addInterceptor(new IndicatorInterceptor(MainActivity.this))
                .execute(new HttpCallback<UserBean>() {
                    @Override
                    public void onSuccess(SuccessResponse<UserBean> response) {
                        Log.e("", "" + response.body());
                    }

                    @Override
                    public void onFailed(ErrorResponse response) {
                        response.code();
                    }
                });
    }


    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.generate_picture:
                request();
                break;
            case R.id.go_to_chart:
                startActivity(new Intent(MainActivity.this, LinearChartActivity.class));
                break;
            case R.id.recycler_sort_by_drag:
                startActivity(new Intent(MainActivity.this, LinearRecyclerActivity.class));
                break;
        }
    }

    private void generate() {
        try {
            InputStream inputStream = getResources().getAssets().open("bkg.png");
            Bitmap background = BitmapFactory.decodeStream(inputStream);
            BitmapDrawable drawable = (BitmapDrawable) getResources().getDrawable(R.mipmap.ic_launcher);
            Bitmap foreground = drawable.getBitmap();
            Bitmap bitmap = combineBitmap(background, foreground);
            File externalFilesDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
            File externalStoragePublicDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
            File outFile = new File(externalStoragePublicDirectory.getAbsolutePath() + File.separator + System.currentTimeMillis() + ".png");
            OutputStream outSream = new FileOutputStream(outFile);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, outSream);
            System.out.print(outFile.getAbsolutePath());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 合并两张bitmap为一张
     *
     * @param background
     * @param foreground
     * @return Bitmap
     */
    public static Bitmap combineBitmap(Bitmap background, Bitmap foreground) {
        if (background == null) {
            return null;
        }
        int bgWidth = background.getWidth();
        int bgHeight = background.getHeight();
        int fgWidth = foreground.getWidth();
        int fgHeight = foreground.getHeight();
        Bitmap newmap = Bitmap.createBitmap(bgWidth, bgHeight, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(newmap);
        canvas.drawBitmap(background, 0, 0, null);
        canvas.drawBitmap(foreground, (bgWidth - fgWidth) / 2,
                (bgHeight - fgHeight) / 2, null);
        canvas.save(Canvas.ALL_SAVE_FLAG);
        canvas.restore();
        return newmap;
    }

}
